//
// Created by LoveHoneyYou on 2024-11-24.
//

#ifndef WEBSERVER_HTTPREQUEST_H
#define WEBSERVER_HTTPREQUEST_H
#include "Buffer.h"
#include <functional>
#include <string>
#include <unordered_map>
#include "HttpResponse.h"
// 当前的解析状态
enum class PrecessState:char
{
    ParseReqLine,
    ParseReqHeaders,
    ParseReqBody,
    ParseReqDone
};

// 定义http请求结构体
class HttpRequest
{
public:
    HttpRequest();
    ~HttpRequest();
    // 重置
    void reset();
    // 添加请求头
    void addHeader(const std::string& key, const std::string& value);
    // 根据key得到请求头的value
    std::string getHeader(const std::string& key);
    // 解析请求行
    bool parseRequestLine(Buffer* readBuf);
    // 解析请求头
    bool parseRequestHeader(Buffer* readBuf);
    // 解析http请求协议
    bool parseHttpRequest(Buffer* readBuf, HttpResponse* response, Buffer* sendBuf, int socket);
    // 处理http请求协议
    bool processHttpRequest(HttpResponse* response);
    // 解码字符串
    std::string decodeMsg(const std::string &from);
    std::string getFileType(const std::string& name);
    static void sendDir(const std::string& dirName, Buffer* sendBuf, int cfd);
    static void sendFile(const std::string& dirName, Buffer* sendBuf, int cfd);

    inline void setMethod(const std::string& method)
    {
        method_ = method;
    }
    inline void seturl(const std::string& url)
    {
        url_ = url;
    }
    inline void setVersion(const std::string &version)
    {
        version_ = version;
    }
    // 获取处理状态
    inline PrecessState getState()
    {
        return curState_;
    }
    inline void setState(PrecessState state)
    {
        curState_ = state;
    }

private:
    char* splitRequestLine(const char* start, const char* end,
                           const char* sub, std::function<void(const std::string&)> callback);
    int hexToDec(char c);

private:
    std::string method_;
    std::string url_;
    std::string version_;
    std::unordered_map<std::string, std::string> reqHeaders_;
    PrecessState curState_;
};


#endif//WEBSERVER_HTTPREQUEST_H
